<template>
  <div class="venus-list-page">
    <!--签约查询界面-->
    <div class="page-search">
      <el-form label-width="160px" style="margin: 20px 50px 20px 0px;" size="mini">
        <el-row type="flex" class="list-items">
          <el-col :span="14">
            <el-form-item label="划款日期:">
              <el-date-picker v-model="table.query_param.settle_date_start" type="date" class="venus-input-middle venus-input-date"
                value-format="yyyyMMdd" placeholder="请输入起始日期" />
              -
              <el-date-picker v-model="table.query_param.settle_date_end" type="date" class="venus-input-middle venus-input-date"
                value-format="yyyyMMdd" placeholder="请输入截止日期" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="产品名称:">
              <el-input v-model="table.query_param.prod_name" class="venus-input-middle" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex" class="list-items">
          <el-col :span="14">
            <el-form-item label="结算日期:">
              <el-date-picker v-model="table.query_param.tradedatestart" type="date" class="venus-input-middle venus-input-date"
                value-format="yyyyMMdd" placeholder="请输入起始日期" />
              -
              <el-date-picker v-model="table.query_param.tradedateend" type="date" class="venus-input-middle venus-input-date"
                value-format="yyyyMMdd" placeholder="请输入截止日期" />
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="流水号:">
              <el-input v-model="table.query_param.dealno" class="venus-input-middle" placeholder="请输入流水号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex" class="list-items">
          <el-col :span="14">
            <el-form-item label="划款指令类型:">
              <el-select v-model="table.query_param.instruct_type" class="venus-input-middle" filterable clearable
                placeholder="--请选择--">
                <el-option v-for="(value,key,index) in dict.instructType" :key="index" :label="value" :value="key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="交易类型:">
              <el-select v-model="table.query_param.dealtype" class="venus-input-middle" filterable clearable
                placeholder="--请选择--">
                <el-option v-for="(value,key,index) in dict.dealType" :key="index" :label="value" :value="key" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <div class="venus-btn-box" style="text-align: center;">
            <el-button type="success" @click="search">查询</el-button>
            <el-button type="info" @click="resetForm">重置</el-button>
            <el-button type="success" @click="submit">提交</el-button>
          </div>
        </el-row>
      </el-form>
    </div>
    <!--    查询列表返显-->
    <div class="page-list">
      <el-row type="flex" justify="space-between" class="page-list-head">
        <div class="title">查询结果</div>
      </el-row>
      <table-pagination @select="mySelect" @select-all="myAllSelect" :table-data="table.query_param.tableData"
        :table-header-config="table.tableHeaderConfig" highlight-current-row :total="table.query_param.total"
        :page-size="table.query_param.limit" :now-page="table.query_param.nowPage" @current-change="handleCurrentChange" />
    </div>
    <div class="page-list">
      <table-pagination @select="mySelect1" @select-all="myAllSelect1" :table-data="table.query_param1.tableData"
        :table-header-config="table.tableHeaderConfig1" highlight-current-row :total="table.query_param1.total"
        :page-size="table.query_param1.limit" :now-page="table.query_param1.nowPage" @current-change="handleCurrentChange1" />
    </div>

    <!-- 模态框 -->
    <el-dialog title="可下载模板列表" :visible.sync="dialog.dialogFormVisible" v-dialogDrag>
      <el-form :model="table.download_param" size="mini" style="text-align: center;">
        <el-row type="flex">
          <el-col>
            <el-form-item label="模板属方:" :label-width="style.formLabelWidth">
              <el-select v-model="table.download_param.temp_name_type" filterable clearable placeholder="请选择">
                <el-option v-for="(value,key,index) in dict.tempNameType" :label="value" :value="key" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="模板名称:" :label-width="style.formLabelWidth">
              <el-input v-model="table.download_param.temp_name" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align: center;">
        <el-button type="success" @click="download_search">查 询</el-button>
      </div>
      <div style="margin-top: 10px;">
        <table-pagination :table-data="table.download_param.tableData" :table-header-config="table.download.tableHeaderConfig"
          highlight-current-row :total="table.download_param.total" :page-size="table.download_param.limit" :now-page="table.download_param.nowPage"
          :operation-config="table.download.operationConfig" @current-change="download_handleCurrentChange" />
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="info" @click="dialog.dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import request from '@/utils/request'
  import * as kk from '@/utils/k-utils'
  import '@/utils/directives'
  export default {
    name: 'BondInfo',
    data() {
      return {
        dict: {
          instructType: [],
          dealType: [],
          tempNameType: []
        },
        table: {
          query_param: {
            //表格一
            limit: 5,
            total: 0,
            nowPage: 1,
            tableData: [], // 表格数据
            exeid: 'queryTransferInfo',
            //查询参数
            settle_date_start: '',
            settle_date_end: '',
            prod_name: '',
            tradedatestart: '',
            tradedateend: '',
            dealno: '',
            instruct_type: '',
            dealtype: '',
          },
          query_param1: {
            limit: 5,
            total: 0,
            nowPage: 1,
            tableData: [], // 表格数据
            exeid: 'intservdealES_001'
          },
          download_param: {
            limit: 5,
            total: 1,
            nowPage: 1,
            tableData: [], // 表格数据
            exeid: 'FINDBILLTEMP',
            //查询参数
            temp_name_type: '',
            temp_name: ''
          },
          tableHeaderConfig: [ // 表头配置
            {
              type: 'selection'
            }, // 多选列
            {
              prop: 'prod_name',
              label: '产品名称'
            },
            {
              prop: 'transfer_date',
              label: '日期'
            },
            {
              prop: 'payunitname',
              label: '付款户名'
            },
            {
              prop: 'incomeunitname',
              label: '收款户名'
            },
            {
              prop: 'pay_money',
              label: '金额'
            },
            {
              prop: 'instruct_type',
              label: '划款类型'
            }
          ],
          tableHeaderConfig1: [ // 表头1配置
            {
              type: 'selection'
            }, // 多选列
            {
              prop: 'dealno',
              label: '交易流水号'
            },
            {
              prop: 'ad_name',
              label: '资产负债品种'
            },
            {
              prop: 'dealtype',
              label: '交易类型'
            },
            {
              prop: 'trans_dir',
              label: '交易方向'
            },
            {
              prop: 'ftool_code',
              label: '资产负债代码'
            },
            {
              prop: 'ftool_name',
              label: '资产负债名称'
            },
            {
              prop: 'grossamount',
              label: '交易金额(元)'
            },
            {
              prop: 'valuedate',
              label: '结算日期'
            },
            {
              prop: 'prod_name',
              label: '产品spv名称'
            }
          ],
          download: {
            tableHeaderConfig: [
              //模态框表格表头配置
              {
                prop: 'temp_type_name',
                label: '模板类型'
              },
              {
                prop: 'temp_name_type',
                label: '模板属方'
              },
              {
                prop: 'temp_name',
                label: '模板名称'
              }
            ],
            operationConfig: {
              fixed: 'right',
              width: 180,
              operationButton: [
                // 每一个操作。value:操作文字；func:回调函数
                {
                  value: '下载',
                  func: this.tempDownload
                }
              ]
            }
          }
        },
        dialog: {
          dialogFormVisible: false
        },
        style: {
          formLabelWidth: '130px'
        },
        selection: {
          table: [],
          table1: []
        },
        sql_params: null,
        echarts_array: [], //存放所有初始化的echarts图表
        Cloud: {} //微服务相关配置
      }
    },
    mounted() {
      // 初始化调用
      this.init()
    },
    methods: {
      init() {
        kk.k_load_dict(this, 'instructType', 't8_instruct_type')
        kk.k_load_dict(this, 'dealType', 't8_dealtype')
        this.commonQuery()

        //系统服务请求地址
        this.Cloud.SYSTEM = "system";
        this.Cloud.PUBLIC = "public";
        this.Cloud.BOND = "bond";
        this.Cloud.CUSTOM = "custom";
        this.Cloud.WORKFLOW = "workflow";
        this.Cloud.SHIBOR = "shibor";
        this.Cloud.IMPAWN = "impawn";
        this.Cloud.DATA = "data";
        this.Cloud.BUYOUT="buyout";
        this.Cloud.FILE="file";
        this.Cloud.FUND="fund";
        this.Cloud.INTSERV="intserv";
        this.Cloud.PROD="prod";
        this.Cloud.FEE="fee";
        this.Cloud.ORG="org";
        this.Cloud.CLEARING="clearing";
        this.Cloud.VAL="val";
        this.Cloud.STACK="stack";
        this.Cloud.DATATOOL="datatool";
        this.Cloud.RISK="risk";
        this.Cloud.CONNECT = "connect";
      },

      search() { // 查询函数
        this.commonQuery()
      },
      //查询参选参数设置
      commonQuery() {
        this.table.query_param.nowPage = 1
        kk.k_load_table(this, 'query_param', 'file')
        this.table.query_param1.dealno = this.table.query_param.dealno
        this.table.query_param1.prod_name = this.table.query_param.prod_name
        this.table.query_param1.tradedatestart = this.table.query_param.tradedatestart
        this.table.query_param1.tradedateend = this.table.query_param.tradedateend
        this.table.query_param1.dealtype = this.table.query_param.dealtype
        this.table.query_param1.nowPage = 1
        kk.k_load_table(this, 'query_param1', 'file')
      },
      //重置
      resetForm() {

      },
      submit() {
        var result_Deal = []; //流水号集
        var result_Transfer = []; //划款指令集
        var result_prod_code = []; //产品代码集
        var result_t8_prod_base_id = []; //产品id集
        //得到两个多选框列的值 判断是否为空
        var Deal = this.selection.table1 //交易流水信息
        var Transfer = this.selection.table //划款指令信息
        if (Deal.length == 0 && Transfer.length == 0) {
          this.$alert('请选择指令或交易信息', '错误', {
            confirmButtonText: '确定',
            callback: action => {}
          })
          return
        }
        for (var i = 0; i < Transfer.length; i++) {
          var id = Transfer[i].id; //划款指令id
          var prod_code = Transfer[i].prod_code; //产品代码
          result_Transfer.push(id);
          result_prod_code.push(prod_code);
        }
        for (var i = 0; i < Deal.length; i++) {
          var dealno = Deal[i].dealno; //流水号
          var t8_prod_base_id = Deal[i].t8_prod_base_id; //产品id
          result_Deal.push(dealno);
          result_t8_prod_base_id.push(t8_prod_base_id);
        }
        if (!this.isAllEqual(result_prod_code)) {
          this.$alert('当前指令不属同一理财', '错误', {
            confirmButtonText: '确定',
            callback: action => {}
          })
          return

        }
        if (!this.isAllEqual(result_t8_prod_base_id)) {
          this.$alert('当前流水不属同一理财', '错误', {
            confirmButtonText: '确定',
            callback: action => {}
          })
          return
        }
        result_Deal.push(0)
        result_Transfer.push(0)
        this.table.download_param.result_Deal = result_Deal.join(",")
        this.table.download_param.result_Transfer = result_Transfer.join(",")
        this.table.download_param.temp_type = '6'
        this.table.download_param.query_withid = 'true'
        this.table.download_param.temp_son_type = ''
        this.table.download_param.pdf = 'false'
        this.openDialog()
      },
      //打开模态框
      openDialog() {
        //获取模板子类型值
        var temp_son_type_key = this.table.download_param.temp_son_type,
          array = temp_son_type_key ? temp_son_type_key.split("+") : [],
          son_type_key_array = [],
          query_withid = this.table.download_param.query_withid || 'false',
          pdf = this.table.download_param.pdf || 'false',
          contain_fieldconf = this.table.download_param.contain_fieldconf || 'false'
        this.table.download_param.query_withid = query_withid.toLowerCase() == 'true' ? '1' : '0';
        this.table.download_param.pdf = pdf.toLowerCase() == 'true' ? '1' : '0';
        this.table.download_param.contain_fieldconf = contain_fieldconf.toLowerCase() == 'true' ? '1' : '0';

        for (var k in array) {
          var temp_son_type_keys = array[k],
            reg = /\{[^\}]+\}/g,
            son_type_key = [],
            endWith = temp_son_type_keys.endWith("$"),
            startsWith = temp_son_type_keys.startsWith("^"),
            temp_son_type_keys = temp_son_type_keys.replace(/\^/g, "").replace(/\$/g, ""),
            keys = temp_son_type_keys.match(reg);
          for (var j in keys) {
            var key = keys[j].replace(/{/g, "").replace(/}/g, "");
            temp_son_type_keys = temp_son_type_keys.replace(keys[j], this.table.download_param[key] ? this.table.download_param[
              key] : "");
          }
          //将包含逗号的参数转化为多个值的并集
          var son_keys_array = temp_son_type_keys.split("_"),
            list = [],
            v = [];
          for (var i in son_keys_array) {
            var p = [];
            list = son_keys_array[i].split(",");
            if (v.length == 0) {
              v = this.deepCopy(list);
            } else {
              for (var m in v) {
                for (var n in list) {
                  p.push(v[m] + "_" + list[n]);
                }
              }
              v = this.deepCopy(p);
            }
          }
          for (var x in v) {
            son_type_key.push("(" + v[x] + ")");
          }
          var str = son_type_key.join("|");
          if (endWith || startsWith) {
            str = (startsWith ? "^" : "") + "(" + str + ")" + (endWith ? "$" : "");
          }
          son_type_key_array.push(str);
        }
        this.table.download_param.temp_son_type = son_type_key_array.join("|")

        //加载数据字典
        kk.k_load_dict(this, 'tempNameType', 'File_BelongTo')
        kk.k_load_table(this, 'download_param', 'file')
        //打开模态框
        this.dialog.dialogFormVisible = true
        this.sql_params = this.deepCopy(this.table.download_param)
      },
      /**
       * 判断数组元素是否全部相同
       * @param array
       * @returns {boolean}
       */
      isAllEqual(array) {
        if (array.length > 0) {
          return !array.some(function(value, index) {
            return value !== array[0]
          });
        } else {
          return true;
        }
      },
      /**
       * 利用递归实现深拷贝
       */
      deepCopy(data) {
        var type = this.getType(data);
        var obj;
        if (type === 'array') {
          obj = [];
        } else if (type === 'object') {
          obj = {};
        } else {
          //不再具有下一层次
          return data;
        }
        if (type === 'array') {
          for (var i = 0, len = data.length; i < len; i++) {
            obj.push(this.deepCopy(data[i]));
          }
        } else if (type === 'object') {
          for (var key in data) {
            obj[key] = this.deepCopy(data[key]);
          }
        }
        return obj;
      },
      /**
       * 获取变量类型
       */
      getType(obj) {
        var toString = Object.prototype.toString;
        var map = {
          '[object Boolean]': 'boolean',
          '[object Number]': 'number',
          '[object String]': 'string',
          '[object Function]': 'function',
          '[object Array]': 'array',
          '[object Date]': 'date',
          '[object RegExp]': 'regExp',
          '[object Undefined]': 'undefined',
          '[object Null]': 'null',
          '[object Object]': 'object'
        };
        return map[toString.call(obj)];
      },
      //selection单选
      mySelect(selection, row) {
        this.selection.table = selection
        console.log(selection)
      },
      //selection全选
      myAllSelect(selection) {
        this.selection.table = selection
      },
      mySelect1(selection, row) {
        this.selection.table1 = selection
        console.log(selection)
      },
      myAllSelect1(selection) {
        this.selection.table1 = selection
      },
      handleCurrentChange(val) {
        this.table.query_param.nowPage = val
        kk.k_load_table(this, 'query_param', 'file')
      },
      handleCurrentChange1(val) {
        this.table.query_param1.nowPage = val
        kk.k_load_table(this, 'query_param1', 'file')
      },
      //模态框搜索
      download_search() {
        this.table.download_param.nowPage = 1
        kk.k_load_table(this, 'download_param', 'file')
      },
      //模态框分页
      download_handleCurrentChange(val) {
        this.table.download_param.nowPage = val
        kk.k_load_table(this, 'download_param', 'file')
      },
      //下载模板
      tempDownload(params, index) {
        params.isZip = 0
        params.t8_temp_info_id = params.id
        $.each(this.echarts_array, function(index, value) {
          var base64 = value["echarts_base64"];
          this.sql_params[value["group_name"]] = base64;
        })
       this.download(this.getSendUrl("file", 'tempDownload.action'), 'www', $.extend(params, this.sql_params))
      },
      download(url, type, params){
            var xhr = new XMLHttpRequest(),
                data = null;
            xhr.open('post', url, true);    // 也可以使用POST方式，根据接口
            xhr.responseType = "blob";  // 返回类型blob
            xhr.withCredentials = true;//支持跨域携带cookie
            if (type == "formdata") {
                data = new FormData();
                data.append("id", "1");
            } else if (type == "json") {
                xhr.setRequestHeader("Content-Type", "application/json");
                data = JSON.stringify(params);
            } else if (type == "text") {
                data = "key=value";
            } else if (type == "www") {
                // 这个header 其实是 传统post 表单的格式
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                data = "";
                $.each(params, function (key, value) {
                    data += "&" + key + "=" + value;
                });
                data = data.length > 0 ? data.substring(1) : data;
            }
            // 定义请求完成的处理函数
            xhr.onload = function () {
                // 请求完成
                if (this.readyState === 4 && this.status === 200) {
                    var name = this.getResponseHeader("Pragma");
                    var blob = this.response;

                    if (window.navigator.msSaveOrOpenBlob) {
                        console.log('IE浏览器');
                        window.navigator.msSaveOrOpenBlob(blob, name);
                    } else {
                        var name = this.getResponseHeader("Pragma");
                        var blob = this.response;
                        var url = URL.createObjectURL(blob);
                        var link = document.createElement('a');
                        link.href = url;
                        link.download = decodeURI(name);
                        link.click();
                        $(link).remove();
                        //$.maskClose();
                    }
                }
            };
            // 发送ajax请求
            xhr.send(data)
      },
      /**
       * 根据service_url和url组装完整请求地址
       * @param service_url	服务地址
       * @param url				请求地址
       * @return					完整请求的具体地址
       */
       getSendUrl (service_url,url) {
          //服务地址，如果没有，再从Cloud.default中取，如果还没有，那就不能访问网关，只能访问本地服务（和之前逻辑一致）
      	if (!service_url){
              service_url = this.Cloud.default;
              console.log("默认服务地址："+service_url);
      	}
          let ZUUL = this.Cloud.zuulUrl;
          if (!service_url){
              ZUUL = "";
              service_url = "";
              console.log("请求本地服务");
          }
          console.log("请求网关："+ZUUL);
          if (ZUUL && !/\/$/.test(ZUUL)){
              ZUUL+="/";
          }
          if (service_url && !/\/$/.test(service_url)){
              service_url+="/";
          }
          //var path = ZUUL+service_url+url;
          var path = "dev/" + service_url + url;
          console.log("请求地址："+path);
          return path;
      }
    }
  }
</script>

<style scoped>
  /*让文本可以被选中*/
  .venus-list-page {
    -moz-user-select: text;
    /*火狐*/
    -webkit-user-select: text;
    /*webkit浏览器*/
    -ms-user-select: text;
    /*IE10*/
    -khtml-user-select: text;
    /*早期浏览器*/
    user-select: text;
  }
</style>
